module(..., package.seeall)

function new(obj)
	local ui = require("ui")

	local menuGroup 	= display.newGroup()
	local boxGroup 		= display.newGroup()
	local scoreGroup 	= nil
	local groupResult	= nil

	local score 	= obj.score
	--thoi gian tra loi cho mot tu
	local times 	= 45
	--
	local xKey		= 240
	--ghi nhan so tu duoc mo ra
	local wordCount = 0
	
	local dataVCNV = obj.dataVCNV
	---------------------------------------------
	--
	---------------------------------------------
	function displayFinish()
		--Hien thong bao het thoi gian phan thi
		if groupResult == nil then
			groupResult = display.newGroup()
			menuGroup:insert(groupResult)		
			
			bgMessage = display.newImage("images/bgMessage.png")
			bgMessage.x = display.contentWidth/2
			bgMessage.y = display.contentHeight/2
			groupResult:insert(bgMessage)
			
			yy = bgMessage.y - bgMessage.height/2 + 40
			displayText(200, groupResult, "BẠN ĐÃ HOÀN THÀNH VCNV", bgMessage.x - bgMessage.width/2 + 56, yy, bgMessage.width - 20, 16, 0, 0, 255)
			
			yy = bgMessage.y - 32
			displayText(500, groupResult, "XIN CHÚC MỪNG BẠN", bgMessage.x - bgMessage.width/2 + 68, yy, bgMessage.width - 20, 18, 0, 0, 255)
			
			yy = bgMessage.y
			displayText(500, groupResult, "ĐÃ DÀNH ĐƯỢC " .. score .. " ĐIỂM", bgMessage.x - bgMessage.width/2 + 58, yy, bgMessage.width - 20, 18, 0, 0, 255)
			
			
			btnDiTiep = ui.newMyButton{
			default = "images/btnDiTiep.png",
			over = "images/btnDiTiepOver.png",
				onRelease = function(event)
					--Tro ve man hinh truoc
					timer.performWithDelay(100, function(event)
						--luu diem so man choi de sang man tiep theo
						obj.score  = obj.score + score
						director:changeScene("tangtoc", obj)
					end, 1)
				end
			}
			btnDiTiep.x = bgMessage.x
			btnDiTiep.y = bgMessage.y + 52
			btnDiTiep.isVisible = false
			groupResult:insert(btnDiTiep)
			
			timer.performWithDelay(1000, function(e)
				btnDiTiep.isVisible = true
				--Luu diem so len server
				timer.performWithDelay(200, submitAccountScore, 1)
			end, 1)
		end
	end
	---------------------------------------------
	--
	---------------------------------------------
	function displayText(delay, group, str, xx, yy, width, fontSize, r, g, b)
		timer.performWithDelay(delay, function(event)
			local words = slipWords(str, ' ')
			local i = 1
			local x = xx
			local y = yy
			while i < #words + 1 do
				local word = display.newText(words[i], 0, 0, native.systemFontBold, fontSize)
				word:setTextColor(r, g, b)
				group:insert(word)
				
				if x + word.width < (xx + width) then
					xx = x + word.width/2
					yy = y
					
					word.x = 480
					word.y = 320
					--Hieu ung bay chu tu goc duoi ben trai
					transition.to(word, {time=100*i, x = xx, y = yy})
					
					x = x + word.width  + 3
				else
					y = y + 20
					x = xx
					
					xx = x + word.width/2
					yy = y
					
					word.x = 480
					word.y = 320
					--Hieu ung bay chu tu goc duoi ben trai
					transition.to(word, {time=100*i, x = xx, y = yy})
					
					x = x + word.width  + 3
				end
				i = i+1
			end
		end, 1)
		return y
	end
	---------------------------------------------
	--
	---------------------------------------------
	function slipWords(str, key)
		local k = 1
		local index = 1
		local data = {}
		while index > 0 do
			local i, j = string.find(str, key, k)
			if i == nil then
				data[index] = str:sub(k)
				--print(data[index])
				index = -1
			else
				--print(i .. " - " .. j)
				local si = str:sub(k, i - 1)
				data[index] = si
				--print(data[index])
				k = j + 1
			end
			index = index + 1
		end
		return data
	end
	---------------------------------------------
	--
	---------------------------------------------
	function showMessageVertical()
		--Khoi tao cau hoi goi y tu hang doc
		if groupVertical == nil then
			groupVertical = display.newGroup()
			menuGroup:insert(groupVertical)		
			
			bgMessage = display.newImage("images/bgMessage.png")
			bgMessage.x = display.contentWidth/2
			bgMessage.y = display.contentHeight/2
			groupVertical:insert(bgMessage)
			
			txt1 = display.newText("Bạn đã hoàn thành 4 từ hàng ngang", 0, 0, native.systemFontBold, 16)
			txt1.x = bgMessage.x
			txt1.y = bgMessage.y - bgMessage.height/2 + 42
			txt1:setTextColor(0, 0, 255)
			groupVertical:insert(txt1)
			
			txt2 = display.newText("Bạn có thêm 30 giây và một gợi ý.", 0, 0, native.systemFontBold, 14)
			txt2.x = bgMessage.x
			txt2.y = bgMessage.y - bgMessage.height/2 + 72
			txt2:setTextColor(0, 0, 255)
			groupVertical:insert(txt2)
			
			txt3 = display.newText("Bạn dành được " .. score .. " điểm", 0, 0, native.systemFontBold, 18)
			txt3.x = bgMessage.x
			txt3.y = bgMessage.y
			txt3:setTextColor(0, 0, 255)
			groupVertical:insert(txt3)
			
			btnDiTiep = ui.newMyButton{
			default = "images/btnDiTiep.png",
			over = "images/btnDiTiepOver.png",
				onRelease = function(event)
					cleanGroups(groupVertical, 0)
					showQuestionsVertical("Bạn có 30 giây để trả lời từ hàng dọc.")
				end
			}
			btnDiTiep.x = bgMessage.x
			btnDiTiep.y = bgMessage.y + 52
			groupVertical:insert(btnDiTiep)
		end
	end
	---------------------------------------------
	--Hien thi goi y tu hang doc
	---------------------------------------------
	function showQuestionsVertical(contents)
		if groupQuestionVertical == nil then
			groupQuestionVertical = display.newGroup()
			groupQuestionVertical.isVisible = false
			groupQuestionVertical:addEventListener( "tap", function( event )
				native.setKeyboardFocus( nil )
			end)
			menuGroup:insert(groupQuestionVertical)
			
			bgAnswer = display.newImage("images/bgAnswer.png")
			bgAnswer.x = display.contentWidth/2
			bgAnswer.y = bgAnswer.height/2
			groupQuestionVertical:insert(bgAnswer)
			
			if system.getInfo( "environment" ) == "simulator" then
				txtAnswer = display.newRect(130, 85, 194, 26)
				txtAnswer:setFillColor(200, 200, 200)
				groupQuestionVertical:insert(txtAnswer)
			else
				txtAnswer = native.newTextField(130, 85, 194, 26, function( event )
						if ( "began" == event.phase ) then
						elseif ( "ended" == event.phase ) then
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtAnswer.font = native.newFont( native.systemFontBold, 14 )
				txtAnswer.inputType = "search"
				groupQuestionVertical:insert(txtAnswer)
			end
			txtAnswer.isVisible = false
			btnBoQua= ui.newMyButton{
				default = "images/btnBoQua.png",
				over = "images/btnBoQuaOver.png",
				onRelease = function(event)
					if groupQuestionVertical then
						cleanGroups(groupQuestionVertical, 0)
						--Dong ban phim
						native.setKeyboardFocus( nil )
						
						if theTimer then
						   timer.cancel(theTimer)	
						end
						displayFinish()
					end
				end
				}
			btnBoQua.x = bgAnswer.x + bgAnswer.width/2 - btnBoQua.width/2 - 3
			btnBoQua.y = bgAnswer.y + bgAnswer.height/2 - btnBoQua.height/2
			groupQuestionVertical:insert(btnBoQua)	
		end
		
		if groupQuestionVertical.isVisible == false and btnWordCurrent then
			--txtAnswer.isVisible = true
			groupQuestionVertical.isVisible = true
			groupQuestionVertical.xScale = 0.2
			groupQuestionVertical.yScale = 0.2

			transition.to(groupQuestionVertical, {time=1500, xScale = 1, yScale = 1, transition=easing.outExpo,
				onComplete = function(event) 
					--bat textbox nhap tu		
					txtAnswer.isVisible = true
					
					groupQuestionVertical.groupWord = display.newGroup()
					groupQuestionVertical:insert(groupQuestionVertical.groupWord)
					--Su kien slide khung hien thi cau hoi da thuc hien xong
					local words = slipWords(contents, ' ')
					local i = 1
					local x = bgAnswer.x - bgAnswer.width/2 + 8
					local y = 12
					while i < #words + 1 do
						local word = display.newText(words[i], 0, 0, native.systemFontBold, 14)
						word:setTextColor(0, 0, 255)
						groupQuestionVertical.groupWord:insert(word)
						
						if x + word.width < bgAnswer.x + bgAnswer.width/2 - 16 then
							xx = x + word.width/2
							yy = y
							
							word.x = 480
							word.y = 320
							--Hieu ung bay chu tu goc duoi ben trai
							transition.to(word, {time=100*i, x = xx, y = yy})
							
							x = x + word.width  + 3
						else
							y = y + 20
							x = bgAnswer.x - bgAnswer.width/2 + 8
							
							xx = x + word.width/2
							yy = y
							
							word.x = 480
							word.y = 320
							--Hieu ung bay chu tu goc duoi ben trai
							transition.to(word, {time=500, x = xx, y = yy})
							
							x = x + word.width  + 3
						end
						i = i+1
					end
				end})
			--Tinh thoi gian tra loi cau hoi
			local begin = function()
				if times > 0 then
					times = times - 1
					showScore()
				else
					if theTimer then
					   timer.cancel(theTimer)	
					end
					--xoa
					cleanGroups(groupQuestionVertical, 0)
					--Dong ban phim
					native.setKeyboardFocus( nil )
					
					local userInput = ""
					if system.getInfo( "environment" ) ~= "simulator" then
						userInput = txtAnswer.text
					end
					--Ket qua tra loi tu hang doc
					if userInput:upper() == btnWordCurrent.words then
						score = score + 20
						--Cap nhat diem do len man hinh
						showScore()
					end
					--cho 5 giay truoc khi qua man tiep theo
					timer.performWithDelay(2000, function(event)
						displayFinish()
					end, 1)
				end
			end
			--doi 2 giay de hien thi xong cau hoi moi bat dau tinh thoi gian
			timer.performWithDelay(2000, function(event)
				times = 30
				theTimer = timer.performWithDelay(1000, begin, 31)
			end, 1)
		end
	end
	---------------------------------------------
	--Hien thi cau hoi tu hang nang
	---------------------------------------------
	function showQuestions(contents)
		if groupQuestion == nil then
			groupQuestion = display.newGroup()
			groupQuestion.isVisible = false
			groupQuestion:addEventListener( "tap", function( event )
				native.setKeyboardFocus( nil )
			end)
			menuGroup:insert(groupQuestion)
			
			bgAnswer = display.newImage("images/bgAnswer.png")
			bgAnswer.x = display.contentWidth/2
			bgAnswer.y = bgAnswer.height/2
			groupQuestion:insert(bgAnswer)
			
			if system.getInfo( "environment" ) == "simulator" then
				txtAnswer = display.newRect(130, 85, 194, 26)
				txtAnswer:setFillColor(200, 200, 200)
				groupQuestion:insert(txtAnswer)
			else
				txtAnswer = native.newTextField(130, 85, 194, 26, function( event )
						if ( "began" == event.phase ) then
						elseif ( "ended" == event.phase ) then
						elseif ( "submitted" == event.phase ) then
							native.setKeyboardFocus( nil )
						end
					end)
				txtAnswer.font = native.newFont( native.systemFontBold, 14 )
				txtAnswer.inputType = "search"
				groupQuestion:insert(txtAnswer)
			end
			txtAnswer.isVisible = false
			
			btnBoQua= ui.newMyButton{
				default = "images/btnBoQua.png",
				over = "images/btnBoQuaOver.png",
				onRelease = function(event)
					if groupQuestion then
						txtAnswer.isVisible = false
						groupQuestion.isVisible = false
						--Hien thi mau xam voi tu hang ngang tuong ung
						displayWordVisible(btnWordCurrent.words, btnWordCurrent.row, btnWordCurrent.indexKey)
						cleanGroups(btnWordCurrent.groupActive, 0)
						--Dong ban phim
						native.setKeyboardFocus( nil )
						
						if theTimer then
						   timer.cancel(theTimer)	
						end
						
						--Da mo het 4 tu hang ngang
						if wordCount == 4 and vertical == nil then
							timer.performWithDelay(2500, function(event)
								showMessageVertical()
							end, 1)
						end
					end
				end
				}
			btnBoQua.x = bgAnswer.x + bgAnswer.width/2 - btnBoQua.width/2 - 3
			btnBoQua.y = bgAnswer.y + bgAnswer.height/2 - btnBoQua.height/2
			groupQuestion:insert(btnBoQua)	
		end
		
		if groupQuestion.isVisible == false and btnWordCurrent then
			--txtAnswer.isVisible = true
			groupQuestion.isVisible = true
			groupQuestion.xScale = 0.2
			groupQuestion.yScale = 0.2
			--Xoa
			if groupQuestion.groupWord ~= nil then
				cleanGroups(groupQuestion.groupWord, 0)
			end
			transition.to(groupQuestion, {time=1500, xScale = 1, yScale = 1, transition=easing.outExpo,
				onComplete = function(event) 
					groupQuestion.groupWord = display.newGroup()
					groupQuestion:insert(groupQuestion.groupWord)
					
					displayText(200, groupQuestion.groupWord, contents, bgAnswer.x - bgAnswer.width/2 + 8, 12, bgAnswer.width - 20, 14, 0, 0, 255)
					--bat textbox nhap tu		
					txtAnswer.isVisible = true
				end})
			--Tinh thoi gian tra loi cau hoi
			local begin = function()
				if times > 0 then
					times = times - 1
					showScore()
				else
					local userInput = "HUE"
					if system.getInfo( "environment" ) ~= "simulator" then
						userInput = txtAnswer.text
					end
					if theTimer then
					   timer.cancel(theTimer)	
					end
					txtAnswer.isVisible = false
					--Dong ban phim
					native.setKeyboardFocus( nil )
					--
					groupQuestion.isVisible = false
					--Ket qua tra lai dung thi mo o chu
					if userInput:upper() == btnWordCurrent.words then
						openWords(btnWordCurrent.words, btnWordCurrent.row, btnWordCurrent.indexKey)
						cleanGroups(btnWordCurrent.groupActive, 0)
						--Tra loi dung mot tu hang ngang dc cong 10 diem
						score = score + 10
						--Cap nhat diem do len man hinh
						showScore()
					else
						--Thong bao sai tu va yeu cau tiep tuc chon tu khac
						displayWordVisible(btnWordCurrent.words, btnWordCurrent.row, btnWordCurrent.indexKey)
						cleanGroups(btnWordCurrent.groupActive, 0)
					end
					--Da mo het 4 tu hang ngang
					if wordCount == 4 then
						--Goi thuc hien 
						timer.performWithDelay(2500, function(event)
							showMessageVertical()
						end, 1)
					end
				end
			end
			--doi 2 giay de hien thi xong cau hoi moi bat dau tinh thoi gian
			timer.performWithDelay(500, function(event)
				theTimer = timer.performWithDelay(1000, begin, 46)
			end, 1)
		end
	end
	---------------------------------------------
	--Hien thi ra dong an tu hang ngang
	---------------------------------------------
	function displayWord(words, row, indexKey)
		local k = 1
		while k <= words:len() do
			ch = words:sub(k, k)
			
			chImg = display.newImage("images/o.png")
			
			chImg.x = (k - indexKey)*34 + xKey
			chImg.y = 62 + (row - 1)*33
			chImg.ch = ch
			chImg.row = row
			boxGroup:insert(chImg)	
			
			k = k + 1
		end
		
		btn = ui.newMyButton{
			default = "images/" .. row .. ".png",
			over = "images/" .. row .. "a.png",
			onRelease = function(event)
				--Chi thuc hien khi khong co hien thi cau hoi len man hinh
				if (groupQuestion == nil or groupQuestion.isVisible == false) and (wordCount < 4)  then
					self = event.target
					if btnWordCurrent and btnWordCurrent ~= self and self.open == false then
						if btnWordCurrent.showWord == false then
							if btnWordCurrent.groupActive then
								btnWordCurrent.open = false
								cleanGroups(btnWordCurrent.groupActive, 0)
							end
						end
					end
					
					if self.open == false and btnWordCurrent ~= self then
						self.open = true
						self.groupActive = displayWordActive(self.words, self.row, self.indexKey)
						--an nut mo tu
						btnOpenWord.isVisible = true
						
						--dat lai thoi gian 45 giay cho cau hoi
						times = 45
						showScore()
						
						btnWordCurrent = self
					end
				end
			end
		}
		btn.x = 20
		btn.y = 62 + (row - 1)*33
		btn.row = row
		btn.words = words
		btn.indexKey = indexKey
		btn.open = false
		btn.showWord = false
		boxGroup:insert(btn)
	end
	---------------------------------------------
	--Thuc hien mo tu hang ngang 
	---------------------------------------------
	function openWords(words, row, indexKey)
		local k = 1
		
		group = display.newGroup()
		
		while k <= words:len() do
			ch = words:sub(k, k)
			
			chImg = display.newImage("images/op.png")
			
			chImg.x = (k - indexKey)*34 + xKey
			chImg.y = 62 + (row - 1)*33
			chImg.ch = ch
			chImg.row = row
			group:insert(chImg)	
			
			chImg.xScale = 0.2
			chImg.yScale = 0.2
			transition.to(chImg, {time=1500, xScale = 1, yScale = 1, transition=easing.outExpo})
			k = k + 1
			
			chText = display.newText( "" .. ch, chImg.x - 7,  chImg.y - 11, "Helvetica", 18)
			chText.x = chImg.x -- chText.width/2
			chText.y = chImg.y -- chText.height/2
			group:insert(chText)	
		end
		boxGroup:insert(group)
		return group
	end
	---------------------------------------------
	--Hien thi noi len hang can tra loi
	---------------------------------------------
	function displayWordActive(words, row, indexKey)
		local k = 1
		
		group = display.newGroup()
		
		while k <= words:len() do
			ch = words:sub(k, k)
			
			chImg = display.newImage("images/oo.png")
			
			chImg.x = (k - indexKey)*34 + xKey
			chImg.y = 62 + (row - 1)*33
			chImg.ch = ch
			chImg.row = row
			group:insert(chImg)	
			
			chImg.xScale = 0.2
			chImg.yScale = 0.2
			transition.to(chImg, {time=1500, xScale = 1, yScale = 1, transition=easing.outExpo})
			k = k + 1
		end
		boxGroup:insert(group)	
		return group
	end
	---------------------------------------------
	--Hien thi hang mau xam khi ko tra loi dc
	---------------------------------------------
	function displayWordVisible(words, row, indexKey)
		local k = 1
		
		group = display.newGroup()
		
		while k <= words:len() do
			ch = words:sub(k, k)
			
			chImg = display.newImage("images/ox.png")
			
			chImg.x = (k - indexKey)*34 + xKey
			chImg.y = 62 + (row - 1)*33
			chImg.ch = ch
			chImg.row = row
			group:insert(chImg)	
			
			chImg.xScale = 0.2
			chImg.yScale = 0.2
			transition.to(chImg, {time=1500, xScale = 1, yScale = 1, transition=easing.outExpo})
			k = k + 1
		end
		boxGroup:insert(group)	
		return group
	end
	---------------------------------------------
	--Hien thi diem so va thoi gian tra loi cau hoi
	---------------------------------------------
	function showScore()
		if scoreGroup == nil then
			scoreGroup = display.newGroup()
		
			bgscore = display.newImage("images/bgscore.png")
			bgscore.x = display.contentWidth - bgscore.width/2
			bgscore.y = display.contentHeight - bgscore.height/2
			
			scoreGroup:insert(bgscore)
			menuGroup:insert(scoreGroup)
		end
		
		if scoreText == nil then
			scoreText = display.newText( "" .. score, bgscore.x,  bgscore.y, "Helvetica", 24)
			scoreText:setTextColor(255, 255, 0)
			scoreText.align = "center"
			scoreGroup:insert( scoreText )	
			
			scoreText.x = bgscore.x + scoreText.width/12
			scoreText.y = bgscore.y + scoreText.height/3
		else
			scoreText.text = "" .. score
		end
		
		if timeText == nil then
			timeText = display.newText( "" .. times, bgscore.x,  bgscore.y, "Helvetica", 14)
			timeText:setTextColor(255, 0, 0)
			timeText.align = "center"
			scoreGroup:insert( timeText )	
			
			timeText.x = bgscore.x + timeText.width/12
			timeText.y = bgscore.y - bgscore.height/2 + timeText.height - 4
		else
			timeText.text = "" .. times
		end
	end
	---------------------------------------------
	--init screen
	---------------------------------------------
	function drawScreen()
		bg = display.newImageRect("images/bg.png", display.contentWidth, display.contentHeight)
		bg.x = display.contentWidth/2
		bg.y = display.contentHeight/2
		menuGroup:insert(bg)
		menuGroup:insert(boxGroup)
		
		btnOpenWord= ui.newMyButton{
			default = "images/btnOpenWord.png",
			over = "images/btnOpenWordOver.png",
			onRelease = function(event)
				if btnWordCurrent and wordCount < 4 then
					if btnWordCurrent.groupActive and btnWordCurrent.showWord == false then
						btnWordCurrent.showWord = true
						btnOpenWord.isVisible = false
						--words = btnOpenWord.words
						showQuestions(dataVCNV[btnWordCurrent.row].questions)
						--Ghi nhan them mot tu duoc mo ra
						wordCount = wordCount + 1
					end
				end
			end
		}
		btnOpenWord.x = 420
		btnOpenWord.y = 16
		btnOpenWord.isVisible = false
		boxGroup:insert(btnOpenWord)	
		--Doc du lieu tu goi cau hoi de thay the doan sau
		--[[displayWord("NUINGU", 1, 4)
		displayWord("HUONG", 2, 1)
		displayWord("HUE", 3, 1)
		displayWord("NHANHAC", 4, 6)
		displayWord("3", 5, 1)
		displayWord("HUDA", 6, 2)
		displayWord("VIDA", 7, 3)
		displayWord("HANMACTU", 8, 5)--]]
		i =1 
		while i <=8 do
			displayWord(dataVCNV[i].words, i, dataVCNV[i].keyIndex)
			i = i + 1
		end
		showScore()
	end
	--Init gameplay screen
	drawScreen()
	---------------------------------------------
	--xoa du lieu
	---------------------------------------------
	function cleanGroups (curGroup, level)
		if curGroup.numChildren then
			while curGroup.numChildren > 0 do
				cleanGroups (curGroup[curGroup.numChildren], level+1)
			end
			if level > 0 then
				curGroup:removeSelf()
				curGroup = nil
			end
		else
			curGroup:removeSelf()
			curGroup = nil
			return
		end
	end
	
	unloadMe = function()
	end
	return menuGroup
end